<template>
  <div id="assessdetail">
    <el-form :model="editForm" label-width="200px" ref="editForm" :inline="true" style="padding:10px 0 0;clear:both" v-show="!pageLoading" :rules="editFormRules">
      <el-row>
        <el-col :span="showUnit?14:24">
          <table cellspacing="0" cellpadding="0" class="mytable">
            <tr>
              <th style="width:120px">标题</th>
              <td>
                <template v-if="readOnly">{{editForm.title}}</template>
                <el-form-item prop="title" v-else>
                  <el-input v-model="editForm.title" style="width:300px"></el-input>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <th>发布日期</th>
              <td>
                <template v-if="readOnly">{{editForm.publishDate}}</template>
                <el-form-item prop="publishDate" v-else>
                  <el-date-picker
                    v-model="editForm.publishDate"
                    type="date"
                    placeholder="发布日期"
                    value-format="yyyy-MM-dd">
                  </el-date-picker>
                </el-form-item>
              </td>
            </tr>
            <tr>
              <th>内容</th>
              <td>
                <div v-if="readOnly" v-html="editForm.content?editForm.content.replace(/\n/g,'<br>'):''"></div>
                <el-input v-else type="textarea" v-model="editForm.content" style="width:100%;" maxlength="4000" show-word-limit :rows="10"></el-input>
              </td>
            </tr>
            <tr v-if="!readOnly">
              <th>附件</th>
              <td>
                <section class="wboxd" style="margin-top:10px;border:1px solid #95B8E7;margin-bottom:10px;">
                  <el-table :data="files" highlight-current-row style="width: 100%;" border>
                    <el-table-column prop="fileName" label="文件名" show-overflow-tooltip>
                      <template slot-scope="scope">
                        {{scope.row.fileName}}{{scope.row.fileType?'.'+scope.row.fileType:''}}
                      </template>
                    </el-table-column>
                    <el-table-column prop="" label="查看权限">
                      <template slot-scope="scope">
                        <el-radio-group v-model="scope.row.fileAuth" v-if="scope.row.fileType==='zip'">
                          <el-radio :label="1">与通知相关</el-radio>
                          <el-radio :label="2">与用户相关</el-radio>
                        </el-radio-group>
                        <template v-else>与通知相关</template>
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                      <template slot-scope="scope">
                        <el-popconfirm title="确定删除该信息吗？" style="margin-left:10px;" @confirm="removeFile(scope.row.id)">
                          <el-button slot="reference" size="small" type="text" icon="el-icon-delete">删除</el-button>
                        </el-popconfirm>
                      </template>
                    </el-table-column>
                  </el-table>
                </section>
                <el-upload
                  class="upload-demo"
                  ref="upload"
                  :action="this.$http.defaults.baseURL+this.$http.defaults.fileDistributionAPI +'api/genFileInfo/upload/'"
                  :on-success="handleUploadSucc"
                  :on-remove="handleRemove"
                  :before-remove="beforeRemove"
                  :on-error="uploadError"
                  :multiple="false"
                  :file-list="fileList"
                  :show-file-list="false"
                  :on-preview="handlePreview"
                  :before-upload="beforeUpload"
                >
                  <el-button type="primary">点击上传</el-button>
                </el-upload>
                <div style="margin-top:20px;">注意：附件查看权限分为“与通知相关”和“与用户相关”两种。“与通知相关”的附件，所有可查看本通知的下发单位用户都可下载；“与用户相关”的附件必须为zip格式，压缩包内文件名需以单位全称命名，单位用户只能下载压缩包内与其单位全称相同的文件。</div>
              </td>
            </tr>
            <tr v-else>
              <th>附件</th>
              <td>
                <section class="wboxd" style="margin-top:10px;border:1px solid #95B8E7;margin-bottom:10px;" v-if="showUnit">
                  <el-table :data="files" highlight-current-row style="width: 100%;" border>
                    <el-table-column prop="fileName" label="文件名" show-overflow-tooltip>
                      <template slot-scope="scope">
                        <a :href="$http.defaults.baseURL+$http.defaults.fileDistributionAPI+'api/genFileInfo/download?id='+scope.row.id">{{scope.row.fileName}}{{scope.row.fileType?'.'+scope.row.fileType:''}}</a>
                      </template>
                    </el-table-column>
                    <el-table-column prop="" label="查看权限">
                      <template slot-scope="scope">
                        <template>{{scope.row.fileAuth===1?'与通知相关':'与用户相关'}}<span v-if="scope.row.subNames">({{scope.row.subNames}})</span></template>
                      </template>
                    </el-table-column>
                  </el-table>
                </section>
                <div v-else>
                  <div v-for="(item,index) in files" :key="index">
                    <a :href="$http.defaults.baseURL+$http.defaults.fileDistributionAPI+'api/genFileInfo/download?id='+item.id">{{item.parentName?item.parentName+'('+item.fileName+')':item.fileName}}{{item.fileType?'.'+item.fileType:''}}</a>
                  </div>
                </div>
              </td>
            </tr>
          </table>
          <template v-if="!readOnly">
            <el-button type="success" @click.native="editFormSubmit()" :loading="saveloading" style="margin-left:20px;">提交</el-button>
          </template>
        </el-col>
        <el-col :span="10" v-show="showUnit">
          <h2 style="margin-top:0">下发单位<span v-if="!editForm.id">（下发单位选定后不可修改）</span></h2>
          <div v-if="!editForm.id" style="clear:both;margin:10px 0;">
            <el-input
              v-model="filterText"
              placeholder="输入关键字进行过滤"
              style="width:220px;margin-right:10px;float:left"
            />
            <template v-if="!readOnly">
              <el-button v-if="selectAllBtn" type="primary" @click="selectTree(1)">全选</el-button>
              <el-button v-else type="primary" plain @click="selectTree(0)">取消</el-button>
            </template>
          </div>
          <span style="line-height:30px;font-weight:bolder">您已选择 {{unitNum}} 家单位</span>
          <div  v-if="!editForm.id" style="clear:both;">
            <el-tree
              ref="tree"
              show-checkbox
              node-key="id"
              :expand-on-click-node="false"
              :data="treedata"
              :filter-node-method="filterNode"
              v-if="!readOnly"
              @check-change="checkChange"
            />
            <el-tree
              default-expand-all
              ref="treeShow"
              node-key="id"
              :expand-on-click-node="false"
              :data="selectTreeData"
              :filter-node-method="filterNode"
              v-else
            />
          </div>
          <div v-else v-html="editForm.unitList.join('<br>')"></div>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
export default {
  watch: {
    timestamp: {
      handler (val) {
        this.unitNum = 0
        // this.$refs['editForm'].resetFields()
        this.getUnits()
        this.editFormReset()
        this.selectTree(0)
        if (this.projectId && this.projectId !== '') {
          this.getDetail(this.projectId)
        }
      },
      immediate: true
    },
    filterText (val) {
      this.$refs.tree.filter(val)
    }
  },
  props: {
    timestamp: '',
    projectId: null,
    readOnly: false,
    showUnit: false
  },
  data () {
    return {
      unitNum: 0,
      removeFileIds: [],
      selectTreeData: [],
      selectAllBtn: true,
      filterText: '',
      treedata: [],
      pageLoading: false,
      saveloading: false,
      editForm: {
        publishDate: '',
        fileId: null,
        projectId: null,
        remark: '',
        title: '',
        unitIds: []
      },
      editFormRules: {
        title: [
          { required: true, message: '必填项', trigger: 'change' }
        ],
        publishDate: [
          { required: true, message: '必填项', trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    getUnits () {
      this.$http
        .get(this.$http.defaults.unitReportAPI + 'api/project/getUnitTree')
        .then(response => {
          if (response.data.success === true) {
            this.treedata = response.data.result
          } else {
            console.log('获取失败:' + response.data.message)
            this.$message({
              message: '获取失败:' + response.data.message,
              type: 'error'
            })
          }
        })
        .catch(error => {
          console.log(error)
        })
    },
    selectTree (flag) {
      if (this.$refs.tree) {
        if (flag) {
          this.selectAllBtn = false
          const keys = []
          for (let i = 0; i < this.treedata.length; i++) {
            keys.push(this.treedata[i].id)
          }
          console.log(keys)
          this.$refs.tree.setCheckedKeys(keys)
        } else {
          this.selectAllBtn = true
          this.$refs.tree.setCheckedKeys([])
          var nodes = this.$refs.tree.store.nodesMap
          for (var i in nodes) {
            nodes[i].expanded = false
          }
        }
      }
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    editFormSubmit (reEnterFlag) {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          let units = []
          if (!this.editForm.id) {
            units = this.$refs.tree.getCheckedNodes().filter(item => item.id < 1000)
            if (!units || units.length === 0) {
              this.$message({
                message: '至少选择一家下发单位',
                type: 'error'
              })
              return false
            }
          }
          this.saveloading = true
          let para = {
            id: this.editForm.id,
            publishDate: this.editForm.publishDate,
            title: this.editForm.title,
            content: this.editForm.content,
            enabled: 1,
            unitNames: this.editForm.unitList && this.editForm.unitList.length > 0 ? this.editForm.unitList : units.map(item => item.label),
            files: this.files && this.files.length > 0 ? this.files.map(item => { return {fileAuth: item.fileAuth, fileId: item.id} }) : null,
            removeFileIds: this.removeFileIds
          }
          let url = 'api/busArticle/save'
          this.$http
            .post(this.$http.defaults.fileDistributionAPI + url, para)
            .then(response => {
              this.saveloading = false
              if (response.data.success) {
                this.editFormReset()
                this.$emit('dialogHide', true)
                this.$message({
                  message: '提交成功！',
                  type: 'success'
                })
              } else {
                this.$message({
                  message: '保存失败:' + response.data.message,
                  type: 'error'
                })
              }
            })
            .catch(error => {
              this.saveloading = false
              console.log(error)
              this.$message({
                message: '网络保存失败:' + error,
                type: 'error'
              })
            })
        }
      })
    },
    editFormReset () {
      this.editForm = {
        publishDate: '',
        fileId: null,
        projectId: null,
        remark: '',
        title: '',
        unitIds: []
      }
      if (this.$refs['editForm']) {
        this.$refs['editForm'].resetFields()
      }
      this.files = []
      this.fileList = []
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
    },
    beforeUpload (file) {
      console.log('文件类型')
      console.log(file.name)
      // const isFormat = file.name.indexOf('.dwtb') > 0
      // // const isLt5M = file.size / 1024 / 1024 < 500
      // if (!isFormat) {
      //   this.$message.error('配置文件只能是 .dwtb 格式!')
      // } else {
      //   this.saveloading = true
      // }
      // return isFormat
    },
    formatFiles (files) {
      if (files && files.length > 0) {
        const newfiles = []
        for (let i = 0; i < files.length; i++) {
          newfiles.push({ name: files[i].fileName + '.' + files[i].fileType, id: files[i].id })
        }
        console.log(newfiles)
        return newfiles
      }
    },
    formatSuccList (fileList) {
      if (fileList && fileList.length > 0) {
        const newfiles = []
        let i = fileList.length - 1
        if (fileList[i].response) {
          newfiles.push({ name: fileList[i].response.result[0].fileName + '.' + fileList[i].response.result[0].fileType, id: fileList[i].response.result[0].id })
        } else {
          newfiles.push(fileList[i])
        }
        console.log(newfiles)
        return newfiles
      }
    },
    removeFile (id) {
      console.log('删除：' + id)
      this.files.splice(this.files.findIndex(item => item.id === id), 1)
      this.removeFileIds.push(id)
      // this.files.splice
    },
    handleUploadSucc (response, file, fileList) {
      this.saveloading = false
      if (response.success) {
        this.files.push({id: response.result[0].id, fileName: response.result[0].fileName, fileType: response.result[0].fileType, fileAuth: 1})
        // this.fileList = this.formatSuccList(fileList)
        this.$message({
          message: '上传成功！' + response.message,
          type: 'success'
        })
      } else {
        this.$message({
          message: '上传失败:' + response.message,
          type: 'error'
        })
      }
    },
    beforeRemove (file, fileList) {
      if (file && file.status === 'success') {
        return this.$confirm(`确定删除 ${file.name}？`)
      }
    },
    handleRemove (file, fileList) {
      if (file && file.status === 'success') {
        console.log(file, fileList)
        const fid = file.id
        const url = 'api/genFileInfo/remove'
        let para = {
          params: {
            id: fid
          }
        }
        this.$http.get(this.$http.defaults.fileDistributionAPI + url, para).then(res => {
          console.log('删除成功:', res)
          if (res.data.success === true) {
            const newfiles = []
            for (let i = 0; i < this.files.length; i++) {
              if (this.files[i].id !== fid) {
                newfiles.push(this.files[i])
              }
            }
            this.files = newfiles
            this.fileList = this.formatFiles(this.files)
            this.$message({
              message: '删除成功！',
              type: 'success'
            })
          }
        })
      }
    },
    uploadError (err) {
      this.saveloading = false
      console.log(err)
      this.$message({
        message: '上传失败:' + err,
        type: 'error'
      })
    },
    handlePreview (file) {
      if (window.navigator.msSaveOrOpenBlob) {
        navigator.msSaveBlob(this.$http.defaults.baseURL + this.$http.defaults.fileDistributionAPI + 'api/genFileInfo/download?id=' + file.id, file.name)
      } else {
        var link = document.createElement('a')
        link.download = file.name
        link.href = this.$http.defaults.baseURL + this.$http.defaults.fileDistributionAPI + 'api/genFileInfo/download?id=' + file.id
        link.click()
        console.log(this.$http.defaults.fileDistributionAPI + 'api/genFileInfo/download?id=' + file.id)
        window.URL.revokeObjectURL(link.href)
      }
    },
    getDetail (id) {
      this.unitNum = 0
      this.removeFileIds = []
      this.pageLoading = true
      this.$http
        .get(this.$http.defaults.fileDistributionAPI + `api/busArticle/getById?id=` + id)
        .then(response => {
          this.editForm = response.data.result
          this.files = response.data.result.fileList.map(item => { return {subNames: item.subNames, fileName: item.fileName, parentName: item.parentName, fileType: item.fileType, id: item.id, fileAuth: item.fileAuth} })
          if (this.readOnly) {
            this.selectTreeData = []
            // this.treedata.forEach(item => {
            //   let showChildren = []
            //   item.children.forEach(it => {
            //     if (response.data.result.unitNames.indexOf(it.id) > -1) {
            //       showChildren.push(it)
            //     }
            //   })
            //   if (showChildren.length > 0) {
            //     item.children = showChildren
            //     this.selectTreeData.push(item)
            //   }
            // })
          } else {
            // this.$refs.tree.setCheckedKeys(response.data.result.unitIds)
          }
          this.unitNum = response.data.result.unitList.length
          this.editForm.projectId = this.editForm.id
          this.pageLoading = false
        })
        .catch(error => {
          this.$message({
            message: '网络获取失败:' + error,
            type: 'error'
          })
        })
    },
    checkChange () {
      this.unitNum = this.$refs.tree.getCheckedKeys().filter(item => item < 1000).length
    }
  }
}
</script>
<style>
#assessdetail .el-upload-list__item{
  width: 250px;
}
#assessdetail a{
  width: 200px;
}
.assessdetail .el-tabs__header{
  height: 29px;
  background: #FAFAFA;
  line-height: 30px;
  font-family: '宋体';
  padding:0 20px;
  border-bottom: 2px solid #E4E7ED;
  margin:0;
}
.assessdetail .el-tabs__item{
  line-height: 30px;
  height: 30px;
  font-weight:bolder;
}
  .cardtab .el-tabs__header{
    padding:0 !important;
    border-bottom:1px solid #E4E7ED;
  }
  #assessdetail .wboxs{
    height:45px;
    padding-top:0;
    margin-bottom: 10px;
  }
  .wboxs{
    padding:5px 15px;
    width: calc(100% - 30px);
    background: #fff;
    border: 1px solid #95B8E7;
    margin:0 10px;
    overflow: hidden;
  }
</style>

<style scoped>
  .tickettable th{
    font-weight:lighter;
    background-image: linear-gradient(to bottom , #f8f8f8, #efefef);
    text-align: center;
  }
  .tickettable{
    width: 100%;
    border-left: 1px solid #95B8E7;
    border-top: 1px solid #95B8E7;
  }
  .tickettable td, .tickettable th{
    padding:5px 10px;
    margin:0;
    font-size:var(--size14) !important;
    line-height: 20px;
    font-family: '宋体';
    border-bottom: 1px solid #95B8E7;
    border-right: 1px solid #95B8E7;
  }
  .tickettable td{
    vertical-align: middle;
    text-align: center;
    font-weight: bolder;
  }
  .mytable{
    border-top: 1px solid #74a6cc;
    border-left: 1px solid #74a6cc;
    margin:0 10px 10px;
    width: calc(100% - 20px);
  }
  .mytable th{
    padding: 10px;
    border-right: 1px solid #74a6cc;
    border-bottom: 1px solid #74a6cc;
    vertical-align: top;
    line-height: 150%;
    background: #FAFAFA;
    width:100px;
    text-align:right;
  }
  .mytable td{
    padding: 10px;
    border-right: 1px solid #74a6cc;
    border-bottom: 1px solid #74a6cc;
    vertical-align: top;
    line-height: 150%;
  }
</style>
